﻿using System;
using System.Management.Automation;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;

namespace MS.InformationManagement.DocumentIDServiceApp.Registration
{
    [Cmdlet(VerbsLifecycle.Install, "DocumentIDService", SupportsShouldProcess = true)]
    [SPCmdlet(RequireUserFarmAdmin = true)]
    internal sealed class InstallDocumentIDService : SPCmdlet
    {
        protected override void InternalProcessRecord()
        {
            // Ensure that the required local farm object is available
            SPFarm farm = SPFarm.Local;
            if (null == farm)
            {
                ThrowTerminatingError(new InvalidOperationException("SharePoint server farm not found."),
                    ErrorCategory.ResourceUnavailable, this);
            }

            // Make sure that the local server is registered in the farm
            SPServer localServer = SPServer.Local;
            if (null == localServer)
            {
                ThrowTerminatingError(new InvalidOperationException("SharePoint local server registration not found."),
                    ErrorCategory.ResourceUnavailable, this);
            }

            if (ShouldProcess("DocumentID Web Service"))
            {
                // Make sure that the sample web service exists
                DocumentIDService service = DocumentIDService.CurrentInstance;
                if (null == service)
                {
                    // Create the service
                    service = new DocumentIDService(farm);
                    service.Update(true);
                }

                // Make sure that the sample web service instance exists for the local server
                DocumentIDServiceInstance serviceInstance = localServer.ServiceInstances.GetValue<DocumentIDServiceInstance>();
                if (null == serviceInstance)
                {
                    // Create the service instance
                    serviceInstance = new DocumentIDServiceInstance(localServer, service);
                    serviceInstance.Update(true);
                }
            }
        }
    }

}
